package com.woniuxy.commentservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.commentclient.client.OrderFeignClient;
import com.woniuxy.commentclient.client.UserFeignClient;
import com.woniuxy.commentclient.client.VenueFeignClient;
import com.woniuxy.commentclient.client.dto.OrderDto;
import com.woniuxy.commentclient.client.dto.UserInfoDto;
import com.woniuxy.commentdao.mapper.CommentMapper;
import com.woniuxy.commentdao.model.Comment;
import com.woniuxy.commentmodel.dto.CommentDto;
import com.woniuxy.commentmodel.param.*;
import com.woniuxy.commentservice.service.CommentService;
import com.woniuxy.commentservice.service.exception.CommentException;
import com.woniuxy.core.model.Result;
import com.woniuxy.core.status.OrderState;
import com.woniuxy.core.status.UserState;
import com.woniuxy.core.util.MyJwtUtil;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.util.MyOssUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 场馆评价表 服务实现类
 * </p>
 *
 * @author 冉杰
 * @since 2024-01-15
 */
@Service
//@GlobalTransactional(rollbackFor = Exception.class)
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private UserFeignClient userFeignClient;
    @Resource
    private VenueFeignClient venueFeignClient;
    @Resource
    private OrderFeignClient orderFeignClient;
    @Resource
    private MyOssUtil myOssUtil;


    /**
     *
     * @param param 新增评论参数列表（场馆id，评论内容，用户id，评论图片（可不传），订单编号，评分）
     */
    @Override
    public void add(AddCommentParam param) {
        Comment one = getOne(new LambdaQueryWrapper<Comment>().eq(Comment::getOrderNum, param.getOrderNum()));
        if (!BeanUtil.isEmpty(one)) throw new CommentException(4001,"该订单已评价，不能重复评价");
        Result<UserInfoDto> userResult = userFeignClient.findUserById(param.getUserId());
        if (!userResult.getFlag()) throw new CommentException(userResult.getCode(),userResult.getMsg());
        UserInfoDto dto = userResult.getData();
        if (dto.getAuthState().intValue()!= UserState.IS_AUTH.getState().intValue())
            throw new CommentException(4002,"实名后才可以进行评价");
        if (dto.getUserState().intValue()!= UserState.IS_ENABLE.getState().intValue())
            throw new CommentException(4003,"用户已被禁用无法评价");
        Result<OrderDto> orderDtoResult = orderFeignClient.findByOrderNum(param.getOrderNum());
        if (!orderDtoResult.getFlag()) throw new CommentException(orderDtoResult.getCode(),orderDtoResult.getMsg());
        OrderDto orderDto = orderDtoResult.getData();
        if (orderDtoResult.getData().getUserId().intValue()!= param.getUserId().intValue())
            throw new CommentException(4002,"只能对自己订单进行评价");
        if (orderDto.getOrderState().intValue()!=OrderState.COMPLETED.getState().intValue())
            throw new CommentException(4005,"已完成订单才能进行评价");
        if (orderDto.getOrderEvaluationState().intValue()== OrderState.IS_EVALUATION.getState().intValue())
            throw new CommentException(4004,"订单已进行过评价");
        Comment comment = BeanUtil.toBean(param, Comment.class);
        comment.setVenueId(orderDto.getVenueId());
        comment.setCommentTime(DateUtil.formatDateTime(new Date()));
        save(comment);
        orderFeignClient.updateOrderEvaluationStateByOrderNum(param.getOrderNum(),OrderState.IS_EVALUATION.getState());
    }

    /**
     *
     * @param param 回复评论参数列表（回复内容，所回复评论id）
     */
    @Override
    public void reply(ReplyParam param) {
        Comment comment = getById(param.getCommentId());
        if (BeanUtil.isEmpty(comment)) throw new CommentException(4006,"评论不存在");
        if (!BeanUtil.isEmpty(comment.getReply())) throw new CommentException(4007,"评论已进行过回复");
        if (comment.getVenueId().intValue()!=param.getVenueId().intValue())
            throw new CommentException(4008,"只能回复自己场馆的评论");
        comment.setReply(param.getReply());
        updateById(comment);
    }

    /**
     *
     * @param param
     * @return
     */

    @Override
    public PageInfo<CommentDto> byPage(CommentByPageParam param) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getVenueId,param.getVenueId());
        Page<Comment> page = new Page<>(param.getPageNum(), param.getPageSize());
        page(page,wrapper);
        List<Comment> records = page.getRecords();
        ArrayList<CommentDto> list = new ArrayList<>();
        for (Comment record : records) {
            Result<UserInfoDto> result = userFeignClient.findUserById(record.getUserId());
            CommentDto commentDto = BeanUtil.toBean(record, CommentDto.class);
            commentDto.setUserAccount(result.getData().getUserAccount());
            list.add(commentDto);
        }
        PageInfo<CommentDto> pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public void venueDel(Integer commentId, Integer venueId) {
        Comment comment = getById(commentId);
        if (comment.getVenueId().intValue()!=venueId.intValue())
            throw new CommentException(4009,"只能删除自己场馆的评论");
        removeById(commentId);
    }

    @Override
    public void replyDel(Integer commentId, Integer venueId) {
        Comment comment = getById(commentId);
        if (comment.getVenueId().intValue()!=venueId.intValue())
            throw new CommentException(4010,"只能删除自己场馆的评论回复");
        comment.setReply(null);
        updateById(comment);
    }

    @Override
    public void userDel(Integer commentId, Integer userId) {
        Comment comment = getById(commentId);
        if (comment.getUserId().intValue()!=userId.intValue())
            throw new CommentException(4011,"只能删除自己发出的评论");
        removeById(commentId);
    }

    @Override
    public void userModify(UserModifyParam param) {
        Comment comment = getById(param.getCommentId());
        if (comment.getUserId().intValue()!=param.getUserId().intValue())
            throw new CommentException(4012,"只能对自己发表的评论进行修改");
        Result<UserInfoDto> userResult = userFeignClient.findUserById(param.getUserId());
        if (!userResult.getFlag()) throw new CommentException(userResult.getCode(),userResult.getMsg());
        UserInfoDto dto = userResult.getData();
        if (dto.getAuthState().intValue()!= UserState.IS_AUTH.getState().intValue())
            throw new CommentException(4002,"实名后才可以进行评价");
        if (dto.getUserState().intValue()!= UserState.IS_ENABLE.getState().intValue())
            throw new CommentException(4003,"用户已被禁用无法评价");
        Result<OrderDto> orderDtoResult = orderFeignClient.findByOrderNum(comment.getOrderNum());
        if (!orderDtoResult.getFlag()) throw new CommentException(orderDtoResult.getCode(),orderDtoResult.getMsg());
        OrderDto orderDto = orderDtoResult.getData();
        if (orderDto.getOrderEvaluationState().intValue()!= OrderState.IS_EVALUATION.getState().intValue())
            throw new CommentException(4012,"已评价的订单才可以进行评价修改");
        comment.setContent(param.getContent());
        comment.setCommentImage(param.getCommentImage());
        comment.setRate(param.getRate());
        comment.setCommentTime(DateUtil.formatDateTime(new Date()));
        updateById(comment);
    }

    @Override
    public void venueModify(VenueModifyParam param) {
        Comment comment = getById(param.getCommentId());
        if (BeanUtil.isEmpty(comment)) throw new CommentException(4006,"评论不存在");
        if (BeanUtil.isEmpty(comment.getReply())) throw new CommentException(4007,"评论未回复过不能进行修改");
        if (comment.getVenueId().intValue()!=param.getVenueId().intValue())
            throw new CommentException(4008,"只能修改自己场馆的回复");
        comment.setReply(param.getReply());
        updateById(comment);
    }

    @Override
    public String upload(MultipartFile file, String orderNum) throws IOException {
        String oldUrl = "";
        String type = FileTypeUtil.getType(file.getInputStream());
        if (!type.equals("jpg")&&!type.equals("png")) throw new CommentException(40001,"文件必须为图片类型");
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        Snowflake snowflake = new Snowflake(1, 1);
        String prefix = snowflake.nextIdStr();
        fileName=prefix+suffix;
        String url = myOssUtil.uploadFile(file.getInputStream(), fileName, "ranjie11");
        return url;
    }
}
